<?php
namespace Helpers;

use Phalcon\Queue\Beanstalk;

class Queue
{

    /**
     * @var \Phalcon\Queue\Beanstalk
     */
    public static $queue;

    public static function init()
    {
        if (!self::$queue) {
            $config = Main::getConfigByName('beanstalk');
            if (!$config) {
                throw new XhException('配置获取失败');
            }
            self::$queue = new Beanstalk($config);
        }
    }

    /**
     * 放置任务并执行
     *
     * @param $action       --动作（方法名）
     * @param $content      --内容（数字）
     * @param array $option --额外选项（beanstalk）
     * @throws XhException
     * @return bool
     *
     * create by ck 20180731
     */
    public static function put($action, $content = [], $option = [])
    {
        self::init();
        if (!is_string($action)) {
            throw new XhException('action必须为字符型');
        }
        if (!self::$queue->put([
            'action'    => $action,
            'content'   => $content
        ], $option)) {
            throw new XhException('投递消息失败');
        }

        $phpExec = Tool::buildPath(Tool::getValue(Main::getConfigByName('phpinfo'), 'prefix'), 'bin/php');
        $script  = Tool::buildPath(BASE_PATH, 'run');
        exec(sprintf('%s %s queue > /dev/null 2>&1 &', $phpExec, $script), $output, $var);
        return true;
    }

    public static function reserve($timeout = null)
    {
        self::init();
        return self::$queue->reserve($timeout);
    }

}